const db = require('../config/database');
const bcrypt = require('bcryptjs');

class User {
    static async create(userData) {
        const { username, password, email } = userData;
        const hashedPassword = await bcrypt.hash(password, 10);
        const [result] = await db.execute(
            'INSERT INTO users (username, password, email) VALUES (?, ?, ?)',
            [username, hashedPassword, email]
        );
        return result.insertId;
    }

    static async findByEmail(email) {
        const [rows] = await db.execute('SELECT * FROM users WHERE email = ?', [email]);
        return rows[0];
    }

    static async findById(id) {
        const [rows] = await db.execute('SELECT * FROM users WHERE user_id = ?', [id]);
        return rows[0];
    }

    static async validatePassword(plainPassword, hashedPassword) {
        return await bcrypt.compare(plainPassword, hashedPassword);
    }

    // 获取用户列表（带分页）
    static async getUsers(limit, offset) {
        try {
            const [rows] = await db.query(
                'SELECT user_id, username, email, created_at, status FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?',
                [parseInt(limit), parseInt(offset)]
            );
            return rows;
        } catch (error) {
            console.error('Error in getUsers:', error);
            throw error;
        }
    }

    // 获取用户总数
    static async getTotalUsers() {
        try {
            const [rows] = await db.query('SELECT COUNT(*) as total FROM users');
            return rows[0].total;
        } catch (error) {
            console.error('Error in getTotalUsers:', error);
            throw error;
        }
    }
}

module.exports = User; 